package com.design.javaManage.config.security.service;

import com.design.javaManage.entity.SysMenu;
import com.design.javaManage.entity.SysUser;
import com.design.javaManage.mapper.SysUserMapper;
import com.design.javaManage.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;


// 实现userDetailsService接口，实现自定义登录逻辑
// 重写loadUserByUsername方法

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;


    @Autowired
    private RedisUtils redisUtils;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //在mapper中自定义登录，根据用户名获取用户信息
        SysUser user;
        if (redisUtils.hasKey("userInfo" + username)) {
            // 缓存中存在用户信息，直接从redis中取
            user = (SysUser) redisUtils.getValue("userInfo_" + username);
            redisUtils.expire("userInfo_" + username,5);
        }else {
            user = userMapper.findByUsername(username);
            if (null == user){
                throw new UsernameNotFoundException("用户名或密码错误！");
            }
            if (user.isAdmin()){
                // 管理员需要查询的角色信息
                user.setRoles(userMapper.findRoles(null));
                user.setPermissions(userMapper.findPermissions(null));
                // 获取父级菜单
                List<SysMenu> menus = userMapper.findMenus(null);
                // 获取子级菜单
                menus.forEach(item -> item.setChildren(userMapper.findChildrenMenu(item.getId(),null)));
                user.setMenus(menus);
            } else {
                // 非管理员需要查询的角色信息
                user.setRoles(userMapper.findRoles(user.getId()));
                user.setPermissions(userMapper.findPermissions(user.getId()));
                // 获取父级菜单
                List<SysMenu> menus = userMapper.findMenus(user.getId());
                // 获取子级菜单
                menus.forEach(item -> item.setChildren(userMapper.findChildrenMenu(item.getId(),user.getId())));
                user.setMenus(menus);
            }
            redisUtils.setValueTime("userInfo_" + username, user, 5);
        }
        return user;
    }
}
